<template>
  <div :class="pageType==='trends'?'upload-container':''">
    <!-- 上传 -->
    <el-upload  :class="pageType==='trends'?'image-uploader':'avatar-uploader'"
               action="#"
                :http-request="HttpRequest"
               :before-upload="beforeUpload"
               accept=".mp4,.mov,.png,.jpeg,.jpg,.pdf,.docx"
               :on-exceed="handleExceed"
               :show-file-list="false">
      <div class="el-upload-dragger" v-if="type===2">
        <i class="el-icon-upload" style="margin-top: -4px"/>
        <div class="el-upload__text" style="margin-top: -90px">+</div>
      </div>

      <div v-else>
        <el-image
          v-if="imageUrl && imageUrl !='NVL' && imageUrl.length>1"
          :src="imageUrl+'?vframe/jpg/offset/0/?imageView2/0/interlace/1/q/29'"
          fit="contain"
          class="avatar"></el-image>
        <!-- <img v-if="imageUrl && imageUrl !='NVL' && imageUrl.length>1" :src="imageUrl" class="avatar"> -->
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </div>

    </el-upload>
    <div class="image-preview"  v-show="imageUrl && imageUrl !='NVL' && imageUrl.length>1 && type===2">
      <div class="image-preview-wrapper">
        <video id="video" height="200" controls="controls" :src="imageUrl" :poster="imageUrl+'?vframe/jpg/offset/0/?imageView2/0/interlace/1/q/29'">
        </video>
      </div>
    </div>
    <!-- 上传列表 -->
    <el-dialog
      append-to-body
      title="上传列表"
      :visible.sync="show_upload"
      @open="open"
      @close="close"
      width="40%">
      <div class="dis-flex flex-wrap">
        <div v-for="(item,index) in list" :key="index" style="width: 100%;border:1px solid #F2F6FC;margin-bottom: 5px;">
          <div class="w-100" style="position: relative;">
            <div style="position: absolute;width: 100%;height: 45px;display: flex;align-items: center;text-align: center;">
              <div style="width: 100%;font-size: 12px;">
                <div style="flex: 1;">{{item.name}}</div>
                <div style="font-weight: bold;">{{parseInt(item.percent)}}%</div>
              </div>
              <div style="width: 80px;">
                <div v-if="item.is_cancel == 0 && item.percent < 100" @click="cancel(index)"><i class="el-icon-circle-close"></i></div>
                <div  v-if="item.is_cancel == 1" style="font-size: 10px;">已取消</div>
                <div v-if="item.is_cancel == 0 && item.percent >= 100" style="font-size: 18px;color: #fff;"><i class="el-icon-success"></i></div>
              </div>
            </div>
            <div class="jdy-progress-bar" :style="{ width: item.percent+'%' ,background:getGradient(item.percent)}"></div>
          </div>
        </div>
      </div>
      <div style="text-align:right;">
        <el-button type="danger" @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="confirmBatch">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import * as qiniu from 'qiniu-js'
import {getQiniuToken, toWaterMark} from "../../api/qiniu";
export default {
  props:{
    title:String,
    type: {
      type: Number,
      default: 1
    },
    value: {
      type: String,
      default: ''
    },
    currentScope: {
      type: Object,
      default: {}
    },
    isWatermark:{
      type: Boolean,
      default: false
    },
    pageType:{
      type: String,
      default: 'trends'
    }
  },
computed: {
    imageUrl() {
      return this.value
    }
  },
  data() {
    return {
      listPercent:[],
      urlList:[],
      uploadPre:"", //上传七牛的文件前缀
      domain: '',//七牛云解析域名
      qiniuToken: '', //七牛Token
      index: 0,
      list: [],
      show_upload:false,
      linearColors: [{ v: 25, s: '#F7564A', e: '#F7564A' }, { v: 50, s: '#F7564A', e: '#F7E04B' }, { v: 100, s: '#F7E04B', e: '#25CCDB', ef: true }, { v: 100, s: '#25CCDB', e: '#25CCDB' }]
    }
  },
  created() {

  },
  methods: {
    HttpRequest(){

    },
    closeDialog(){
      this.show_upload=false
    },
    close(){
      //窗口关闭时取消所有进度
      this.list.forEach((item,index)=>{
        this.cancel(index)
      })
    },
    open(){
      this.list=[]
      this.index=0
      this.urlList=[]
    },
    confirmBatch(){
      let flag = true
      this.list.forEach(item=>{
        if (item.percent!==100&&item.is_cancel===0){
          flag = false
        }
      })
      if (!flag){
        this.$notify({
          title: '失败',
          message: "请等待所有文件上传成功 或 出现了网络问题，请刷新页面重新上传！",
          type: 'error',
          duration: 2000
        })
      }else{
        //请求父组件，添加素材列表
        this.$emit('input', this.urlList[0].url)
        if (this.type===3){
          this.$emit('inputWithWatermarkVideoMethod', this.urlList[0].url.replace("materialSharing","watermark"),this.currentScope)
        }
        if (this.type===1){
          this.$emit('inputWithWatermarkImgMethod', this.urlList[0].url.replace("materialSharing","watermark"),this.currentScope)
        }

        this.show_upload=false
      }
    },
    toWaterMark(url){
      toWaterMark({"type":this.type,"url":url}).then(response => {

      })
    },
    hasSpecialSymbols(str) {
      var regex = /[ `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/
      return regex.test(str)
    },
    removeSpecialCharacters(str) {
      return str.replace(/[^\w\s]/gi, '') // 使用正则表达式 /[^\w\s]/g 匹配非单词、非空白字符并全局替换为空字符串 ''
    },
    beforeUpload(file) {
      //检查文件的名称(这里暂不做限制，上传之前修改文件名，去除特殊字符)
      // var period = file.name.lastIndexOf('.')
      // var splitFileName = file.name.substring(0, period)
      // if (this.hasSpecialSymbols(splitFileName)) {
      //   this.$message.error('文件名称中存在特殊字符请修改后上传：' + splitFileName + '文件')
      //   return false // 终止上传
      // }

      let typeArr = file.type.split('/');
      if (this.type ==1 && typeArr[0] != 'image') {
        this.$message.error('图片文件格式错误!不支持'+file.type+'文件');
        return false; // 终止上传
      }else if (this.type ==2 && typeArr[0] != 'video'){
        this.$message.error('视频文件格式错误!不支持'+file.type+'文件');
        return false; // 终止上传
      }else {
        this.show_upload = true;
        this.getQiniuToken(file);
      }
    },
    uploadVideo(file, index) {
      const _this = this;
      let indexd = file.name.lastIndexOf('.');
      let suffix = file.name.substring(indexd);
      let prefix = file.name.substring(0, indexd);

      //判断是否有特殊字符
      if (this.hasSpecialSymbols(prefix)) {
        prefix = this.removeSpecialCharacters(prefix)
      }
      // key：文件资源名，为空字符串时则文件资源名也为空，为 null 或者 undefined 时则自动使用文件的 hash 作为文件名
      const key = _this.uploadPre+'/' + prefix + '_' + Date.now() + suffix;
      _this.list.push({
        is_cancel: 0, //是否取消
        name: key, //上传文件名
        percent: 0, //进度
        subscription: null, //取消对象
        imgLink: '' //缩略图
      })
      // _this.qiniuToken 由后端提供，通过接口获取
      var observable = qiniu.upload(file, key, _this.qiniuToken, {
        useCdnDomain: true,
        region: qiniu.region.z0, // 根据地区不同，官网有不同的配置
        concurrentRequestLimit: 1000,
      });
      var observer = {
        next(res) { // 用于展示上传进度
          _this.list[index].percent = res.total.percent;
        },
        error(err) {
          console.log({err})
          _this.$message({
            type: 'warning',
            message: err.message + ',刷新页面重试!'
          })
        },
        complete(res) {
          let url = _this.domain +"/"+ res.key;
          let urlParam = {"url":url};
          _this.urlList.push(urlParam)
          if (_this.isWatermark){
            _this.toWaterMark(url)
          }


        },
      };
      this.list[index].subscription = observable.subscribe(observer); // 开始上传（赋值给一个全局的参数，可以在合适的时机通过：subscription.unsubscribe() 终止上传）
    },
    //取消上传
    cancel(index) {
      this.list[index].subscription.unsubscribe();
      this.list[index].is_cancel = 1;
    },
    //获取Token
    getQiniuToken(file) {//1图片 2视频
      getQiniuToken({"type":this.type}).then(res => {
        if (res.code == 200) {
          this.qiniuToken = res.data.qiniuToken;
          this.domain = res.data.domain
          this.uploadPre = res.data.uploadPre
          this.uploadVideo(file, this.index); // 上传视频到七牛云
          this.index = this.index + 1;
        }
      })
    },
    // 选取文件超过数量提示
    handleExceed(files, fileList) {
      this.$message.warning(`最多可选择5个文件,本次选择了 ${files.length} 个文件`);
    },
    getGradient (percentage) {
      let linecolor = this.getColorItem(percentage)
      if (linecolor) {
        return 'linear-gradient(90deg,' + linecolor.s + ',' + linecolor.e + ')'
      } else {
        return ''
      }
    },
    // 根据进度 获取颜色数组
    getColorItem (p) {
      let mp = p
      for (let sub of this.linearColors) {
        if (!sub.ef && mp <= sub.v) {
          return sub
        } else if (sub.ef && mp < sub.v) {
          return sub
        }
      }
      return null
    }
  }
}
</script>
<style>
.jdy-progress-bar {
  transition: width 1s;
  height: 45px;
}

</style>


<style scoped="scoped">

.avatar-uploader ::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader ::v-deep .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: contain;
}

</style>


<style rel="stylesheet/scss" lang="scss" scoped>
@import "src/styles/mixin.scss";
.upload-container {
  width: 100%;
  position: relative;
  @include clearfix;
  .image-uploader {
    width: 60%;
    float: left;
  }
  .image-preview {
    // width: 200px;
    height: 50px;
    position: relative;
    border: 1px dashed #d9d9d9;
    //float: left;
    margin-left: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
    .image-preview-wrapper {
      position: relative;
      width: 100%;
      // height: 100%;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .image-preview-action {
      position: absolute;
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
      cursor: default;
      text-align: center;
      color: #fff;
      opacity: 0;
      font-size: 20px;
      background-color: rgba(0, 0, 0, .5);
      transition: opacity .3s;
      cursor: pointer;
      text-align: center;
      line-height: 200px;
      .el-icon-delete {
        font-size: 36px;
      }
    }
    &:hover {
      .image-preview-action {
        opacity: 1;
      }
    }
  }
}
</style>
<style scoped>
.upload-container {
  .el-upload {
    width: 100%;

    .el-upload-dragger {
      width: 100%;
      height: 50px;
    }
  }
}
</style>
